package com.onejson.ojmall.controller;

import org.thymeleaf.TemplateEngine;
import com.itextpdf.text.pdf.BaseFont;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.Context;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/pdf")
@Api(tags = "pdf管理")
public class PdfController {


    /**
     * 通过html模板生成pdf
     * @param response
     * @throws Exception
     */
    @GetMapping("/export/html2pdf")
    public void export(HttpServletResponse response) throws Exception {
        // 设置响应头
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=report.pdf");

        // 加载HTML模板
        InputStream templateInputStream = this.getClass().getResourceAsStream("/templates/pdfTemplate.html");
        assert templateInputStream != null;
        byte[] bytes = new byte[templateInputStream.available()];
        templateInputStream.read(bytes);
        String htmlContent = new String(bytes, StandardCharsets.UTF_8);

        // 准备上下文数据
        Context context = new Context();

        context.setVariable("title", "测试");

        // 渲染HTML
        TemplateEngine templateEngine = new TemplateEngine();
        String processedHtml = templateEngine.process(htmlContent, context);

        // 将HTML转换为PDF
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(processedHtml);
        // 字段导入很重要，不然中文不显示
        renderer.getFontResolver().addFont("/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        renderer.layout();

        // 输出PDF
        try (OutputStream outputStream = response.getOutputStream()) {
            renderer.createPDF(outputStream);
        }
    }
}